#!/usr/bin/env node

const net = require('net');

// 检查端口是否被占用的函数
function checkPortAvailable(port) {
  return new Promise((resolve) => {
    const server = net.createServer();

    server.on('error', (err) => {
      if (err.code === 'EADDRINUSE') {
        console.log(`端口 ${port} 被占用`);
        resolve(false);
      } else {
        console.log(`端口 ${port} 检查出错: ${err.message}`);
        resolve(false);
      }
    });

    server.listen(port, () => {
      server.close(() => {
        console.log(`端口 ${port} 可用`);
        resolve(true);
      });
    });
  });
}

async function test() {
  const port = process.argv[2] || 8090;
  console.log(`测试端口 ${port}...`);
  const isAvailable = await checkPortAvailable(port);
  console.log(`端口 ${port} 是否可用: ${isAvailable}`);
}

test();